'use client';

import { useChat } from '@ai-sdk/react';
import { useEffect, useRef, useState } from 'react';
import EastIcon from '@mui/icons-material/East';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import CheckIcon from '@mui/icons-material/Check';
import { useParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
import ReactMarkdown from 'react-markdown';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
// 修改为浅色风格
import { oneLight } from 'react-syntax-highlighter/dist/cjs/styles/prism';
import copy from 'copy-to-clipboard';

export default function Page() {
    const { chat_id } = useParams();
    const { data: chat } = useQuery({
        queryKey: ['chat', chat_id],
        queryFn: () => {
            return axios.post('/api/get-chat', {
                chat_id: chat_id,
            })
        }
    })

    const { data: preMessages } = useQuery({
        queryKey: ['messages', chat_id],
        queryFn: () => {
            return axios.post('/api/get-messages', {
                chat_id: chat_id,
                chat_user_id: chat?.data?.userId
            })
        },
        enabled: !!chat?.data?.id
    })
    const [model, setModel] = useState("deepseek-v3");
    const handleChangeModel = () => {
        setModel(model === 'deepseek-v3' ? 'deepseek-r1' : 'deepseek-v3');
    };
    // { messages, model, chat_id, chat_user_id }
    const { messages, input, handleInputChange, handleSubmit, append } = useChat({
        body: {
            model: model,
            chat_id: chat_id,
            chat_user_id: chat?.data?.userId,
        },
        initialMessages: preMessages?.data
    });
    const endRef = useRef<HTMLDivElement>(null);
    useEffect(() => {
        if (endRef.current) {
            endRef.current.scrollIntoView({ behavior: 'smooth' });
        }
    }, [messages]);

    const handelFirstMessage = async (model: string) => {
        if (chat?.data?.title && preMessages?.data?.length === 0) {
            // eslint-disable-next-line @typescript-eslint/no-unused-expressions
            await append({
                role: 'user',
                content: chat?.data?.title,
            }), {
                model: model,
                chat_id: chat_id,
                chat_user_id: chat?.data?.userId,
            }
        }
    }

    useEffect(() => {
        setModel(chat?.data?.model)
        handelFirstMessage(chat?.data?.model)
    }, [chat?.data?.title, preMessages])
    // 添加复制状态管理
    const [copiedMessageId, setCopiedMessageId] = useState<string | null>(null);

    // 复制消息内容
    const handleCopyMessage = (content: string, messageId: string) => {
        copy(content);
        setCopiedMessageId(messageId);
        setTimeout(() => {
            setCopiedMessageId(null);
        }, 2000);
    };

    // 处理回车键提交
    const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSubmit();
        }
    };

    return (
        <div className='flex flex-col h-screen justify-between items-center bg-gray-50' >
            <div className='flex flex-col w-3/4 md:w-2/3 gap-8 overflow-y-auto scrollbar-hide justify-between flex-1 px-4'>
                <div className='h-4'></div>
                <div className='flex flex-col gap-8 flex-1'>
                    {messages?.map(message => (
                        <div
                            key={message.id}
                            className={`rounded-lg flex flex-row ${message?.role === 'assistant' ? 'justify-start mr-18' : "justify-end ml-10"}`}
                        >
                            <div className={`relative group inline-block p-3 rounded-lg shadow-sm ${message?.role === 'assistant'
                                ? 'bg-blue-50/90 text-blue-800 border-l-4 border-blue-500/80'
                                : 'bg-white/95 text-gray-800 border-r-4 border-gray-400/70'
                                }`}>
                                {/* 复制按钮移至右下角 */}
                                <button
                                    className="absolute bottom-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity p-1 rounded-full bg-gray-100/80 hover:bg-gray-200/90 backdrop-blur-sm"
                                    onClick={() => handleCopyMessage(message.content, message.id)}
                                >
                                    {copiedMessageId === message.id ? (
                                        <CheckIcon fontSize="small" className="text-green-600/90" />
                                    ) : (
                                        <ContentCopyIcon fontSize="small" className="text-gray-600/80" />
                                    )}
                                </button>

                                {/* Markdown 渲染 */}
                                <div className="markdown-content prose prose-sm max-w-none">
                                    <ReactMarkdown
                                        components={{
                                            code({ node, inline, className, children, ...props }) {
                                                const match = /language-(\w+)/.exec(className || '');
                                                return !inline && match ? (
                                                    <div className="relative rounded-md overflow-hidden border border-gray-200/70 shadow-sm">
                                                        <SyntaxHighlighter
                                                            style={oneLight}
                                                            language={match[1]}
                                                            PreTag="div"
                                                            customStyle={{
                                                                margin: 0,
                                                                padding: '1rem',
                                                                borderRadius: '0.375rem',
                                                                backgroundColor: 'rgba(255, 255, 255, 0.85)',
                                                                backdropFilter: 'blur(4px)',
                                                            }}
                                                            {...props}
                                                        >
                                                            {String(children).replace(/\n$/, '')}
                                                        </SyntaxHighlighter>
                                                        <button
                                                            className="absolute bottom-2 right-2 p-1 rounded-md bg-gray-200/80 hover:bg-gray-300/90 text-gray-700 text-xs shadow-sm backdrop-blur-sm transition-all duration-200"
                                                            onClick={() => copy(String(children))}
                                                        >
                                                            复制
                                                        </button>
                                                    </div>
                                                ) : (
                                                    <code className={`${className} bg-gray-100 px-1 py-0.5 rounded text-gray-800`} {...props}>
                                                        {children}
                                                    </code>
                                                );
                                            }
                                        }}
                                    >
                                        {message.content}
                                    </ReactMarkdown>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
                <div className='h-4' ref={endRef}>

                </div>
            </div>

            {/* 输入框 */}
            <div className="flex flex-col items-center justify-center mt-4 shadow-md border-[1px] border-gray-200/80 rounded-lg w-3/4 md:w-2/3 mb-4 bg-white/95 hover:shadow-lg transition-all duration-300 backdrop-blur-sm">
                <textarea
                    className="w-full rounded-t-lg p-3 h-24 focus:outline-none resize-none bg-transparent"
                    value={input}
                    onChange={handleInputChange}
                    onKeyDown={handleKeyDown}
                    placeholder="请输入您的问题..."
                >
                </textarea>
                <div className="flex flex-row items-center justify-between w-full h-12 px-3 py-2 bg-gray-50/90 rounded-b-lg border-t border-gray-100/80">
                    <div>
                        <div className={`flex flex-row items-center justify-center rounded-lg border-[1px] px-3 py-1 cursor-pointer transition-all duration-200 hover:shadow-sm ${model === 'deepseek-r1'
                            ? "border-blue-400/80 bg-blue-50/90 text-blue-600"
                            : "border-gray-300/70 hover:border-blue-300/80 hover:bg-blue-50/80"
                            }`}
                            onClick={handleChangeModel}
                        >
                            <p className="text-sm font-medium">
                                深度思考(R1)
                            </p>
                        </div>
                    </div>
                    <div className="flex items-center justify-center border-2 border-blue-500/80 p-1.5 rounded-full cursor-pointer hover:bg-blue-50/80 transition-all duration-200 hover:shadow-md"
                        onClick={handleSubmit}
                    >
                        <EastIcon className="text-blue-500/90" />
                    </div>
                </div>
            </div>
        </div>
    );
}